package com.tojabo.link;

public class DoublyLinkedList {

	private Link first;
	private Link last;
	
	public DoublyLinkedList(){
		first =null;
		last = null;
	}
	
	public void insertFirst(long dd){
		Link newLink = new Link(dd);
		
		if(isEmpty()){
			last = newLink;
			first = newLink;
		}else{
			newLink.next=first;
			first.previous=newLink;			
			first = newLink;
		}
		
	}
	
	public void insertAfter(long dd){
		Link newLink = new Link(dd);
		
		if(isEmpty()){
			first = newLink;
			last = newLink;
		}else{
			newLink.previous =last;
			last.next = newLink;			
			last = newLink;
		}
				
	}
	
	public Link deleteFirst(){
		Link temp = first;
		
		if(first.next==null){
			last=null;
			first = first.next;
		}else{
			first = first.next;
			first.previous = null;	
		}
		
		return temp;
	}
	
	public Link deleteAfter(){
		Link temp = last;
		
		if(last.previous==null){
			first = null;
			last = last.previous;
		}else{
			last = last.previous;
			last.next=null;
		}
		
		return temp;
	}
	
	public boolean isEmpty(){
		return (first==null);
	}
	
	public void displayForward(){
		System.out.print("List(first-->last): ");
		Link current = first;
		while(current!=null){
			current.diaplayLink();
			current = current.next;
		}
		System.out.println(" ");
	}
	
	public void displayBackward(){
		System.out.print("List(last -->first): ");
		Link current = last;
		while(current!=null){
			current.diaplayLink();
			current = current.previous;
		}
		System.out.println(" ");
	}
	
	class Link{
		public long dData;
		public Link next;
		public Link previous;
		
		public Link(long dd){
			dData = dd;
		}
		
		public void diaplayLink(){
			System.out.print(dData+" ");
		}
	}
}
